<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>动态数据源管理</title>

    <script type="text/javascript" th:src="${front.vue_js}" src="webjars/dynamic-datasource-ui/vue/vue.js"></script>
    <script type="text/javascript" th:src="${front.axios_js}" src="webjars/dynamic-datasource-ui/axios/axios.min.js"></script>
    <link th:href="${front.iview_css}" rel="stylesheet" href="webjars/dynamic-datasource-ui/iview/style/iview.css"/>
    <script type="text/javascript" th:src="${front.iview_js}" src="webjars/dynamic-datasource-ui/iview/iview.min.js"></script>
</head>
<body>
<div id="app-user"></div>


<div id="app-log">


    <i-Form ref="formSearchUser" :model="datasource" :label-width="60" inline>

        <Form-Item label="key" prop="key">
            <i-Input type="text" v-model="datasource.key" placeholder="数据源key" >
            </i-Input>
        </Form-Item>
        <Form-Item label="url" prop="url">
            <i-Input type="text" v-model="datasource.url" placeholder="jdbc连接" style="width: 600px" >
            </i-Input>
        </Form-Item>
        <Form-Item label="username" prop="username">
            <i-Input type="text" v-model="datasource.username" placeholder="数据库用户名">
            </i-Input>
        </Form-Item>
        <Form-Item label="password" prop="password">
            <i-Input type="text" v-model="datasource.password" placeholder="数据库密码">
            </i-Input>
        </Form-Item>


        <Form-Item>
            <i-Button type="primary" @click="addDataSource">新增数据源</i-Button>
        </Form-Item>
    </i-Form>


    <i-table size="small" :columns="log.columns" :data="log.data" @on-selection-change="onSelectionChange"></i-table>


</div>


<!-- 在js中使用模板变量 带有模板的入口页面 -->
<script type="text/javascript" th:inline="javascript">

    //全局变量
    Vue.prototype.baseUrl = "/";


    var springfox = {
        "getBaseUrl": function() {
            var baseUrl;
            if (baseUrl === undefined) {
                var urlMatches = /(.*)\/dynamic-datasource.html.*/.exec(window.location.href);
                baseUrl = urlMatches[1];
            }
            return baseUrl;
        }
    };
    console.log(springfox.getBaseUrl())
    Vue.prototype.baseUrl = springfox.getBaseUrl()

    Date.prototype.Format = function (fmt) { //
        let o = {
            "M+": this.getMonth() + 1,                 //月份
            "d+": this.getDate(),                    //日
            "h+": this.getHours(),                   //小时
            "m+": this.getMinutes(),                 //分
            "s+": this.getSeconds(),                 //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            "S": this.getMilliseconds()             //毫秒
        };
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    }


    //封装axios
    const instance = axios.create({
        baseURL: Vue.prototype.baseUrl,
        timeout: 1000000,
        withCredentials: true//跨域
    });
    // 添加响应拦截器
    instance.interceptors.response.use(function (response) {
        // 对响应数据做点什么
        return response;
    }, function (error) {
        // 对响应错误做点什么
        if (error.status == 403) {
            logVM.log.form.isAddModalShow = true;
            window.globalConfig.user = "";
            // 补充requestId提示
            logVM.$Modal.warning({
                title: '提示403',
                content: error.data.msg + "<br> requestId:" + error.headers.requestid
            });
        }
        return Promise.reject(error);
    });
    // 添加请求拦截器
    instance.interceptors.request.use(
        config => {
            var timestamp = new Date().getTime();
            config.headers = {
                ...config.headers,
                "timestamp": timestamp
            }
            return config
        }, function (error) {
            return Promise.reject(error)
        }
    );

    Vue.prototype.axios = instance;

    var logVM = new Vue({
        el: '#app-log',
        data: {
            //user:window.globalConfig.user,
            datasource: {
                key: "db_xxx",
                url: "jdbc:mysql://192.168.4.187:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true",
                username: '',
                password: ''
            },
            formInline: {
                username: '',
                password: ''
            },

            log: {
                // 列表数据
                data: [],
                pageNum: 1,
                pageSize: 10,
                total: 10,
                columns: [
                    // 行勾选框
                    {
                        type: 'selection',
                        width: 60,
                        align: 'center'
                    },
                    {title: 'key', key: 'key'},
                    {title: 'url', key: 'url', width:300},
                    {title: 'username', key: 'username'},
                    {title: 'password', key: 'password', width: 200},

                    {
                        title: '操作', key: 'action',

                        render: (h, params) => {
                            return h('div', [
/*                                h('Button', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {marginRight: '5px'},
                                    on: {
                                        click: () => {
                                            userVM.userShow(params.index);
                                        }
                                    }
                                }, '检查'),
                                h('Button', {
                                    props: {type: 'success', size: 'small'},
                                    style: {marginRight: '5px'},
                                    on: {
                                        click: () => {
                                            userVM.modalShowUserEdit(params.index);
                                        }
                                    }
                                }, 'Edit'),*/
                                h('Button', {
                                    props: {
                                        type: 'error', size: 'small'
                                    },
                                    on: {
                                        click: () => {
                                            logVM.logRemove(params.index)
                                        }
                                    }
                                }, '移除')
                            ]);
                        }
                    }],
                // 被选中行
                selectedItem: [],
                // 查询表单模型
                formSearch: {
                    model: {
                        logId: '',
                        type: '',
                        title: '',
                        description: '',
                    }
                },
                // 添加/修改表单模型
                form: {
                    isEditModalShow: false,
                    isAddModalShow: false,
                    model: {
                        logId: '',
                        type: '',
                        title: '',
                        description: '',
                        ip: '',
                        requestUri: '',
                        method: '',
                        params: '',
                        exception: '',
                        operateDate: '',
                        timeout: '',
                        loginName: '',
                        requestId: '',
                        dataSnapshot: '',
                        requestTimestamp: '',
                        status: ''
                    }
                }
            }

        },
        created: function () {

            this.loadLogs(this.log.pageNum, this.log.pageSize);

        }
        ,
        methods: {

            // 重置表单
            handleResetFields(name) {
                var vm = this;
                this.$refs[name].resetFields();
            }
            ,
            // 提交查询
            handleSearchSubmit() {
                this.loadLogs(0, this.log.pageSize);
            }
            ,
            //分页加载数据
            loadLogs: function (pageNum, pageSize) {
                var vm = this;

                this.axios.get('dynamic-datasource-ui/list', {
                    params: {}
                }).then(function (response) {
                    vm.log.data = response.data.data;

                })
            }
            ,
            //页码变更
            logChangePage: function (val) {
                this.log.pageNum = val;
                this.loadLogs(this.log.pageNum, this.log.pageSize);
                console.log(val);
            }
            ,
            //页大小变更
            logChangePageSize: function (val) {
                this.log.pageSize = val;
                this.loadLogs(this.log.pageNum, this.log.pageSize);
                console.log(val);
            }
            ,
            // 添加数据
            logAdd: function () {
                var vm = this
                this.axios.get('login', {
                    params: {username: vm.formInline.username, password: vm.formInline.password}
                }).then(function (response) {
                    var result = response.data;
                    if (result.success) {
                        vm.$Message.success(result.msg);
                    } else {
                        vm.$Message.warning(result.msg);
                    }
                })
                    .catch(function (error) {
                        vm.$Message.error('Fail!' + error.data.msg);
                    })
            }

            ,
            // 删除记录
            logRemove(index) {
                var vm = this;
                var record = this.log.data[index];
                this.log.data.splice(index, 1);
                this.axios.delete('dynamic-datasource-ui/remove', {
                    params: {
                        key: record.key
                    }
                }).then(function (response) {

                    var result = response.data;
                    if (result.success) {
                        vm.$Message.success(result.message);
                    } else {
                        vm.$Message.warning(result.message);
                        vm.loadLogs(vm.log.pageNum, vm.log.pageSize);
                    }

                })
            }
            ,
            // 多选数据变化,批量删除依赖
            onSelectionChange(selection) {
                this.log.selectedItem = selection;
                console.log('选中数据dd:' + selection);
            }
            ,
            // 批量删除
            batchDelete() {
                var vm = this;
                var records = this.log.selectedItem;
                this.axios.delete('log/batchDelete', {
                    data: records
                }).then(function (response) {
                    if (response.data.success) {
                        vm.$Modal.success({
                            title: '提示',
                            content: response.data.msg
                        });
                    } else {
                        vm.$Modal.warning({
                            title: '提示',
                            content: response.data.msg
                        });
                    }
                    vm.loadLogs(vm.log.pageNum, vm.log.pageSize);
                })
            }
            ,
            // xxx批量操作
            batchOperate() {
                var vm = this;
                var records = this.log.selectedItem;
                vm.$Modal.warning({
                    title: '提示',
                    content: JSON.stringify(records) + '<br>后端需要实现/batchOperate接口'
                });
                this.axios.post('log/batchOperate', records).then(function (response) {
                    if (response.data.success) {
                        vm.$Modal.success({
                            title: '提示',
                            content: response.data.msg
                        });
                    } else {
                        vm.$Modal.warning({
                            title: '提示',
                            content: response.data.msg
                        });
                    }
                    vm.loadLogs(vm.log.pageNum, vm.log.pageSize);
                })
            }
            ,







            // 新增数据源
            addDataSource: function () {
                var vm = this;
                var model = vm.datasource;

                this.axios.post('/dynamic-datasource-ui/add', {
                    key: model.key,
                    url: model.url,
                    username: model.username,
                    password: model.password
                }).then(function (response) {
                    if (response.data.success) {
                        vm.$Modal.success({
                            title: '提示',
                            content: response.data.message
                        });
                    } else {
                        vm.$Modal.warning({
                            title: '提示',
                            content: response.data.message
                        });
                    }
                    vm.loadLogs(vm.log.pageNum, vm.log.pageSize);
                }).catch(function (error) {

                })
            },
        }
    })

</script>


</body>
</html>